#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    showMaximized();
    thread.append(new MyThread());
    thread.append(new MyThread());



}

MainWindow::~MainWindow()
{
    socket_stop();
   // thread3.stop();
   // thread3.wait();
    delete ui;
}
void MainWindow::socket_stop(){
    foreach(MyThread *t,thread){
       t->stop();
       t->wait();

    }
}

void MainWindow::on_pushButton_clicked()
{
    socket_start();
    ui->pushButton->setEnabled(false);
   // thread3.init_socket();
}
void MainWindow::socket_start(){
    int flag=1;
   foreach(MyThread *t,thread){
       if(t->init_socket()==0){
            flag=0;
       }
   }
   if(flag==1){
       qDebug("总体连接成功");
       return ;
   }else{
       socket_close();
       socket_start();
   }
}

void MainWindow::on_pushButton_2_clicked()
{
    socket_close();
    ui->pushButton->setEnabled(true);
    //thread3.close_socket();

}
void MainWindow::socket_close(){
    foreach(MyThread *t,thread){
       t->send_op(OP::OP_CLOSE);
       t->close_socket();
    }
}
void MainWindow::socket_sendfile(){
    hassend=0;
    QFileInfo finfo(filename);
    int bansize=finfo.size()/thread.length();
    int tmp=0;
    int count=1;
    foreach(MyThread *t,thread){
        t->on();
        if(count==thread.length()){
         t->setReadInof(tmp,finfo.size()-tmp);
        }else{
         t->setReadInof(tmp,bansize);

        }
        t->readfile(filename);
        t->start();
        tmp+=bansize;
        count++;
    }

}

void MainWindow::on_pushButton_3_clicked()
{




socket_sendfile();

   // thread.on();
   // thread2.on();
   // thread3.on();


   // thread.setReadInof(0,bansize);
    //thread2.setReadInof(bansize,finfo.size()-bansize);
   // thread3.setReadInof(200000,319789-200000);
   // thread.readfile(filename);
   // thread2.readfile(filename);
    //thread3.readfile(filename);
   // ui->Ip->setText("file size:"+QString::number(len));
  // thread.start();
   //thread2.start();
   // thread3.start();
   // QImage tmpimage;

    //QBuffer buf;
  //  QDataStream in(&buf);
   // in << image;
   // qint64 length=sizeof(quint32)+buffer.data().size();
   // QByteArray ba=QByteArray(buf.data().data(),buf.size());
  // out<<buffer.data();
   // out.setVersion(QDataStream::Qt_5_4);
  //  out<<*image;

  //  QBuffer buf;

    //buf.open(QIODevice::ReadWrite);
  //  QDataStream in(&buf);
   // in.setVersion(QDataStream::Qt_5_4);
    //in << content;
    /*
    QByteArray content;
    QFile f2("a.dat");
    f2.open(QIODevice::ReadOnly);
    QDataStream out(&f2);
    out.setVersion(QDataStream::Qt_5_4);
    out>>content;
    f2.close();
    */
  //  QImage tmp;
 //   tmp.loadFromData(content);
   // f.close();
  //  QByteArray ba;
   // in >> ba;
    //out << ba;
   // tmpimage.loadFromData(ba);
   // ui->Ip->setText(QString::number(tmpimage.width())+QString::number(tmpimage.height())+",size:"+QString::number(buf.size()));
//ui->Ip->setText(QString::number(tmp.height()));

   //  int rlen= content.size();
    // Common::send_size(rlen,tcpsocket);
    // thread.tcpsocket=tcpsocket;
    // thread.content=content;
    // thread.start();

   //  thread.wait();
/*
     int relsendsize=0;
     while(relsendsize<content.size()){
          send_size(relsendsize);
          relsendsize+=tcpsocket->write(content.data()+relsendsize,1024);
          QThread::msleep(1);
     }
    ui->Ip->setText(QString::number(relsendsize));
    */
  //   ui->Ip->setText(QString::number(len.length())+","+QString::number(content.size())+",send:"+QString::number(sendsize)+"relsend:"+QString::number(relsendsize));
   //  QImage *scaleimage;
   //  QImage tmpimage;
    // tmpimage=tmp.scaled(231,311,Qt::KeepAspectRatio);
    // scaleimage=&tmpimage;
    // ui->imagelable->setPixmap(QPixmap::fromImage(*scaleimage));

}

void Common::send_size(int size,QTcpSocket *tcpsocket){
    QByteArray len;

    QDataStream in(&len,QIODevice::WriteOnly|QIODevice::Truncate);
    in<<size;
    tcpsocket->write(len.data(),len.size());
    tcpsocket->waitForBytesWritten(10);

    QThread::msleep(10);




}
void MyThread::send_op(char op){
    Common::send_data(QByteArray(&op,sizeof(op)),tcpsocket);

}

void Common::send_string(QString content,QTcpSocket *tcpsocket){
    QByteArray len;
    len=content.toLatin1();
    tcpsocket->write(len.data(),len.size());
    tcpsocket->waitForBytesWritten(10);
    QThread::msleep(10);
}
void Common::send_data(QByteArray content,QTcpSocket *tcpsocket){
    tcpsocket->write(content.data(),content.size());

    tcpsocket->waitForBytesWritten(10);
    QThread::msleep(10);
}


void MainWindow::on_pushButton_4_clicked()
{
     filename=QFileDialog::getOpenFileName(this,
                                              tr("选择图像"),
                                              "F:\\",
                                        tr("Images (*.png *.bmp *.jpg *.tif *.GIF )"));
    if(!filename.isEmpty()){

        image.load(filename);
        QImage *scaleimage;
        QImage tmpimage;
        tmpimage=image.scaled(231,311,Qt::KeepAspectRatio);
        scaleimage=&tmpimage;
        ui->imagelable->setPixmap(QPixmap::fromImage(*scaleimage));

    }

}
void MyThread::stop(){
    stoped=false;
}
void MyThread::on(){
    stoped=true;
}
QByteArray MyThread::convertJpData(JpData jdata){
    char *p_char;
    p_char = reinterpret_cast<char*>(&jdata);
    QByteArray readdata(p_char, sizeof(jdata));
    return readdata;
}
void MyThread::setReadInof(int seek, int readcount){

     start_seek=seek;
     read_size=readcount;
}

int MyThread::init_socket(){

    tcpsocket=new QTcpSocket(this);
    connect(tcpsocket,SIGNAL(readyRead()),this,SLOT(recv()));
    tcpsocket->connectToHost(QHostAddress(hostip),port);
    if(!tcpsocket->waitForConnected(2)){

     tcpsocket->disconnectFromHost();
     return 0;

    }else{
      return 1;
    }

}
void MyThread::close_socket(){

    stop();
    tcpsocket->disconnectFromHost();

    qDebug("断开与服务器的链接");
}
void MyThread::recv(){

    qDebug(tcpsocket->readAll());

}
int MyThread::readfile(QString filename){
    char tmpchar=OP::OP_FILE;
    QByteArray qbyte=QByteArray(&tmpchar,sizeof(tmpchar));

    Common::send_data(qbyte,tcpsocket);


    QFileInfo finfo(filename);
    QFile f(filename);
    JpData jpdata;
    f.open(QIODevice::ReadWrite);
    f.seek(start_seek);
    content=f.read(read_size);

    jpdata.file_size= f.size();
    jpdata.send_size=content.size();

    QString fname=finfo.fileName();
    memcpy(jpdata.filename,fname.toLatin1().data(),fname.toLatin1().size()+3);

    jpdata.sigl_block=block;
    jpdata.waveid=1;
    jpdata.seek=start_seek;
    qDebug("JpData(包大小:%d):\n文件总字节数:%d\n此次将要接受字节数:%d\n次发送字节数:%d\n仓库id:%d\n文件起始位置:%d\n文件名:%s\n",sizeof(jpdata),jpdata.file_size,jpdata.send_size,jpdata.sigl_block,jpdata.waveid
           ,jpdata.seek,jpdata.filename);

    QByteArray data=convertJpData(jpdata);


    Common::send_data(data,tcpsocket);
    f.close();
    return jpdata.file_size;
}


void MyThread::run(){

    int relsendsize=0;
    int successnums=0;

    while(stoped&&relsendsize<content.size()){

        Common::send_size(relsendsize,tcpsocket);
        if(relsendsize+block>content.size()){

            successnums=tcpsocket->write(content.data()+relsendsize,content.size()-relsendsize);

            relsendsize+=successnums;
        }else{

            successnums=tcpsocket->write(content.data()+relsendsize,block);
            relsendsize+=successnums;

        }
        tcpsocket->waitForBytesWritten(30);
        QThread::msleep(30);


    }
    Common::send_size(-1,tcpsocket);
    hassend=hassend+content.size();
    //发送已经发送大小
    Common::send_size(hassend,tcpsocket);
    qDebug("发送完毕:%ld",hassend);

}
